<template>
  <div>
    <!-- 查询表单 -->
    <el-form :inline="true" class="mb-4">
      <el-form-item label="编码">
        <el-input v-model="query.code" style="width:200px" placeholder="请输入编码" clearable />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="query.status" placeholder="请选择状态" style="width:160px" clearable>
          <el-option label="全部" :value="null" />
          <el-option label="待审核" :value="1" />
          <el-option label="已审核" :value="2" />
          <el-option label="已驳回" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="单据日期：">
        <el-date-picker
          v-model="query.dateRange"
          type="daterange"
          range-separator="至"
          :start-placeholder="query.dateRange[0] || '开始'"
          :end-placeholder="query.dateRange[1] || '结束'"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchPage(1)">查询</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据列表 -->
    <TestPage
      @row-audit="openAudit"
      :table-data="list"
      :columns="columns"
      :current-page="page"
      :total="total"
      :page-size="size"
      @page-change="fetchPage"
      @action="handleTableAction"
      @edit="openEditDialog"
      @delete="handleDelete"
    />

    <!-- 审核对话框 -->
    <el-dialog v-model="auditVisible" title="审核调拨单" width="500px">
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="80px">
        <el-form-item label="单号：">
          <el-input v-model="auditForm.code" disabled />
        </el-form-item>
        <el-form-item label="结果：" prop="pass">
          <el-select v-model="auditForm.pass" placeholder="请选择">
            <el-option label="通过" :value="true" />
            <el-option label="不通过" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item label="意见：">
          <el-input type="textarea" v-model="auditForm.comment" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="auditVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import request from '@/util/request'
import { ElMessageBox, ElMessage } from 'element-plus'
import TestPage from '@/test/TestPage.vue'
import { useRouter } from 'vue-router'
import type { ProMove, Good } from '@/types/kc/KCDB'
import type { OutStoreOrder, outStoreDetail } from '@/types/kc/outStore'
import type { InStoreOrder, InStoreDetail } from '@/types/kc/InStore'

// 分页 & 查询
const page = ref(1), size = ref(5), total = ref(0)
const list = ref<ProMove[]>([])
const query = reactive<{ code: string; status: number|null; dateRange: [string,string]|[] }>({
  code: '', status: null, dateRange: []
})

// 列定义
const columns = ref([
  { prop:'id',label:'ID' },
  { prop:'code',label:'编码' },
  { prop:'date',label:'单据日期' },
  { prop:'status',label:'状态' },
  { prop:'skid',label:'仓管人ID' },
  { prop:'delFlag',label:'删除状态' },
  { prop:'createDate',label:'创建时间' },
  { prop:'createUser',label:'创建人' },
  { prop:'updateDate',label:'更新时间' },
  { prop:'updateUser',label:'更新人' }
])

// 审核对话
const auditVisible = ref(false)
const auditFormRef = ref()
const auditForm = reactive({ code:'', pass: null as boolean|null, comment: '' })
const auditRules = reactive({ pass: [{ required:true, message:'请选择结果', trigger:'change' }] })
let current: ProMove|null = null

// 时间格式
function fmtDate(d: Date, end=false){
  const z=(n:number)=>n.toString().padStart(2,'0')
  const Y=d.getFullYear(), M=z(d.getMonth()+1), D=z(d.getDate())
  return end?`${Y}-${M}-${D} 23:59:59`:`${Y}-${M}-${D} 00:00:00`
}

// 拉取分页
async function fetchPage(p:number){
  const ps=new URLSearchParams()
  ps.append('pageNow',p+''); ps.append('pageSize',size.value+'')
  if(query.code) ps.append('code',query.code)
  if(query.status!=null) ps.append('status',query.status+'')
  if(query.dateRange.length===2){
    const [s,e]=query.dateRange.map(x=>new Date(x))
    ps.append('startDate',fmtDate(s,false))
    ps.append('endDate',fmtDate(e,true))
  }
  const r=await request.post('kc/proMove/getProMovePage', ps)
  const d=r.data.data
  list.value=d.list||[]
  total.value=d.total||0
  page.value=d.pageNo||p
}

// 重置条件
function reset() {
  query.code = ''
  query.status = null
  query.dateRange = []
  fetchPage(1)
}

// 操作按钮
function handleTableAction(actionName: string) {
  if (actionName === 'add') {
    router.push({ name: 'Addcpcx' })
  }
}

// 编辑 & 删除
const router = useRouter()

function openEditDialog(row: ProMove) {
  router.push({ name: 'EditCPCX', params: { code: row.code } })
}

async function handleDelete(row: ProMove) {
  try {
    await ElMessageBox.confirm(
      '确定要删除该条记录吗？此操作不可恢复！',
      '警告',
      { type: 'warning' }
    )
    await request.post(
      'kc/proDivide/delProDivide',
      new URLSearchParams({ code: row.code }),
      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
    )
    ElMessage.success('删除成功')
    fetchPage(page.value)
  } catch (err) {
    if (err === 'cancel') {
      ElMessage.info('已取消删除')
    } else {
      ElMessage.error('删除失败')
      console.error(err)
    }
  }
}


// 打开审核框
function openAudit(row:ProMove){
  current=row
  auditForm.code=row.code; auditForm.pass=null; auditForm.comment=''
  auditVisible.value=true
}

// 提交审核并生成出入库
async function submitAudit(){
  await auditFormRef.value.validate()
  // 1. 调拨审核
  await request.post('kc/proMove/check', new URLSearchParams({
    code: auditForm.code,
    status: auditForm.pass? '3':'2',   // 2=通过
    checkComment: auditForm.comment
  }))
  ElMessage.success('审核完成')
  auditVisible.value=false

  // if(auditForm.pass && current){
  //   // 2. 取详情
  //   const det=await request.get('/proMove/getOneProMove',{ params:{ code: current.code } })
  //   const move=det.data.data as ProMove
  //   // 3. 生成出库/入库
  //   const { outOrder, outDetails, inOrder, inDetails } = transform(move)
  //   // 出库
  //   await request.post('kc/outStore/addOutStore', outOrder)
  //   await Promise.all(outDetails.map(d=>request.post('kc/outStoreDetail/addOutStoreDetail', d)))
  //   outDetails.forEach(d=>{
  //     request.post('kc/StoreGoodSummary/method',{ sid:d.storeId, gid:d.goodId, stock:-d.count, sumCost:d.outStoreSumCost })
  //   })
  //   request.post('workflowDesign/workFlow/startProcess',{ code: outOrder.code, type:6 })

  //   // 入库
  //   await request.post('/inStore/addInStore', inOrder)
  //   await Promise.all(inDetails.map(d=>request.post('kc/inStoreDetail/addInStoreDetail', d)))
  //   inDetails.forEach(d=>{
  //     request.post('kc/StoreGoodSummary/method',{ sid:d.storeId, gid:d.goodId, stock:d.count, sumCost:d.inStoreSumCost })
  //   })
  //   request.post('workflowDesign/workFlow/startProcess',{ code: inOrder.inStoreCode, type:5 })

  //   ElMessage.success('生成出入库单成功')
  // }

  fetchPage(page.value)
}

// // 组装出入库单头明细
// function transform(m:ProMove){
//   // 出库单头
//   const outOrder: OutStoreOrder = {
//     id:0, code:m.code, orderDate:new Date(m.date), sourceCode:m.code,
//     cid:0, businessmanId:0, deptId:0, orderStatus:0,
//     storeManId:m.skid, orderTypeId:0, typeId:7,
//     outStoreSumPrice:0, createId:0, createDate:new Date(),
//     updateId:0, updateDate:new Date(), isDelete:0
//   }
//   const outDetails: outStoreDetail[] = m.goods.map((g:Good, i)=>{
//     const cnt = m.counts[i] || 0
//     return {
//       id:0, outStoreCode:m.code, goodId:g.id,
//       goodsCode:g.code, goodsName:g.name, tax:g.tax||0,
//       count:cnt, notes:'', storeId:m.osids[i]||m.osids[0],
//       storeName:'', unit:'', singlePrice:g.tax||0,
//       taxSinglePrice:g.tax||0,
//       taxSumPrice:(g.tax||0)*cnt,
//       sumPrice:(g.tax||0)*cnt,
//       outStoreSingleCost:g.tax||0,
//       outStoreSumCost:(g.tax||0)*cnt,
//       isDelete:0, createId:0, createDate:new Date(),
//       updateId:0, updateDate:new Date()
//     }
//   })
//   outOrder.outStoreSumPrice = outDetails.reduce((s,d)=>s+d.outStoreSumCost,0)

//   // 入库单头
//   const inOrder: InStoreOrder = {
//     id:0, inStoreCode:m.code,
//     goodId:0, goodsCode:'', goodsName:'',
//     count:0, notes:'', storeId:0, storeName:'',
//     taxSumPrice:0, sumPrice:0,
//     inStoreSingleCost:0, inStoreSumCost:0,
//     isDelete:0, createId:0, createDate:new Date(),
//     updateId:0, updateDate:new Date()
//   }
//   // 明细
//   const inDetails: InStoreDetail[] = m.goods.map((g,i)=>{
//     const cnt=m.counts[i]||0
//     return {
//       id:0, inStoreCode:m.code, goodId:g.id,
//       goodsCode:g.code, goodsName:g.name,
//       count:cnt, notes:'',
//       storeId:m.isids[i]||m.isids[0],
//       storeName:'', taxSumPrice:(g.tax||0)*cnt,
//       sumPrice:(g.tax||0)*cnt,
//       inStoreSingleCost:g.tax||0,
//       inStoreSumCost:(g.tax||0)*cnt,
//       isDelete:0, createId:0,
//       createDate:new Date(), updateId:0,
//       updateDate:new Date()
//     }
//   })

//   return { outOrder, outDetails, inOrder, inDetails }
// }

// 首次加载
fetchPage(1)
</script>

<style scoped>
.mb-4 { margin-bottom:16px }
</style>
